﻿/* 
 * author: www.cnblogs.com/luminji
 * date  : 2012/01/28
 * desc  : In this class, we use a dynamic argument. Because of this argument can be HttpResponseBase and HttpResponse ( or HttpRequestBase and HttpRequest). But, HttpResponseBase and HttpResponse don't have any relations between each other. So we use dynamic.
 */
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using Luminji.Core.Json;

namespace Luminji.Core.Web.Cookie
{
    public class CookieHelper
    {

        public static void SetCookieValue(dynamic response, string cookieName, string value)
        {
            HttpCookie myCookie = new HttpCookie(cookieName, value);
            response.Cookies.Add(myCookie);
        }

        public static void SetCookieValue<T>(dynamic response, string cookieName, T value)
        {
            SetCookieValue(response, cookieName, JsonHelper.ToJson<T>(value));
        }

        public static string GetCookieValue(dynamic request, string cookieName)
        {
            HttpCookie myCookie = request.Cookies[cookieName];
            if (myCookie != null)
            {
                return myCookie.Value;
            }
            return null;
        }

        public static TOut GetCookieValue<TOut>(dynamic request, string cookieName) where TOut : class
        {
            string json = GetCookieValue(request, cookieName);
            if (string.IsNullOrEmpty(json))
            {
                return null;
            }
            return JsonHelper.ToModel<TOut>(json);
        }

        public static void DeleteCookieValue(dynamic response, string cookieName)
        {
            HttpCookie cookie = new HttpCookie(cookieName, null);
            cookie.Expires = new DateTime(1900, 1, 1);
            //response.Cookies.Add(cookie);
            if (response.Cookies[cookieName].Value != null)
            {
                response.Cookies[cookieName].Value = null;
            }
        }

    }
}
